# coding=utf-8
"""
base handler
Author: kaspar
Date: 2022-03-31
"""
from tornado.web import RequestHandler
import json
from util.config import Config
from util.logger import Logger

class BaseHandler(RequestHandler):
    """
    base handler class
    """
    def initialize(self):
        """
        init
        """
        self._result = {"status": 1, "msg": ""}
        self._token = Config.get_conf("authentication", "token")

    def check_content_type(self):
        """
        check content type
        """
        content_type = self.request.headers.get('Content-Type', None)
        if content_type is None:
            Logger.writelog("error", "header no Content-Type")
            raise Exception('content_type error')
        if "application/json" != content_type:
            Logger.writelog("error", "Content-Type is error")
            raise Exception('content_type error')
        return 0

    def response(self):
        """
        response function
        """
        self.gen_response_header()
        self.write(json.dumps(self._result))

    def check_param(self):
        """
        check param json
        """
        try:
            self._post_params = json.loads(self.request.body)
        except Exception as e:
            raise Exception("param is not json")

    def gen_response_header(self):
        """
        get response_header
        """
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', \
                        'x-requested-with, Content-Type')
        self.set_header('Access-Control-Allow-Methods', \
                        'POST, GET, PUT, DELETE, OPTIONS')

    def options(self):
        """
        option api
        """
        self.gen_response_header()
        self.set_status(204)
        self.finish()